package cn.springcloud.fix.common.starter.aspect;

import cn.springcloud.fix.common.core.utils.IpUtil;
import cn.springcloud.fix.common.core.utils.WebUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Aspect
@Component
public class RequestLogAspect {

    @Pointcut(value = "execution(* cn.springcloud.fix.*.controller.*.*(..))")
    private void pointcut() {
    }

    @Around("pointcut()")
    public Object interceptor(ProceedingJoinPoint joinPoint) throws Throwable {
        //不要捕获异常，往上抛出，可能会出现 runtime exception:cn.springcloud.fix.common.core.base.R cannot be cast to cn.springcloud.fix.common.core.base.Result
        //或者返回明确的returnType类型对象
        long startTime = System.currentTimeMillis();
        HttpServletRequest request = WebUtil.getRequest();
        String ip = IpUtil.getIP(request);
        String strClassName = joinPoint.getTarget().getClass().getName();
        String strMethodName = joinPoint.getSignature().getName();
        String url = request.getRequestURL().toString();
        log.info("请求IP:【{}】,请求URL:【{}】,类名:【{} ,方法:【{}】", ip, url, strClassName, strMethodName);

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Class<?> returnType = signature.getReturnType();

        Object obj = joinPoint.proceed();

        long duration = System.currentTimeMillis() - startTime;
        log.info("请求IP:【{}】,请求URL:【{}】, 耗时：【{}】", ip, url, duration);
        return obj;
    }
}
